package com.liwei.lwmail.order.service.impl;

import com.liwei.lwmail.order.entity.OrderEntity;
import com.liwei.lwmail.order.entity.OrderReturnReasonEntity;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liwei.common.utils.PageUtils;
import com.liwei.common.utils.Query;

import com.liwei.lwmail.order.dao.OrderItemDao;
import com.liwei.lwmail.order.entity.OrderItemEntity;
import com.liwei.lwmail.order.service.OrderItemService;

@RabbitListener(queues = {"atguigu"})
@Service("orderItemService")
public class OrderItemServiceImpl extends ServiceImpl<OrderItemDao, OrderItemEntity> implements OrderItemService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderItemEntity> page = this.page(
                new Query<OrderItemEntity>().getPage(params),
                new QueryWrapper<OrderItemEntity>()
        );

        return new PageUtils(page);
    }

    /**
     *
     * @param msg 完整的消息
     * @param entity 发送的消息对象类型
     * @param channel 当前传输数据的通道
     */
    @RabbitHandler
    public void receiveMsg(Message msg, OrderReturnReasonEntity entity, Channel channel) throws IOException {
        System.out.println("接受的消息内容为:"+entity);
        //deliveryTag在channel中自增
        long deliveryTag = msg.getMessageProperties().getDeliveryTag();
        //手动确认
        if (deliveryTag % 2 == 0){
            //签收
            channel.basicAck(deliveryTag,false);//true:批量确认,false确认当前消息
            System.out.println("签收了"+deliveryTag+"号消息");
        }else {
            //拒绝
            channel.basicNack(deliveryTag,false,false);
            System.out.println("重新入队了"+deliveryTag+"号消息");
//            System.out.println("丢弃并入队了"+deliveryTag+"号消息");
        }
    }
    @RabbitHandler
    public void receiveMsg2(Message msg, OrderEntity entity, Channel channel) throws IOException {
        System.out.println("接受的消息内容为:"+entity);
        long deliveryTag = msg.getMessageProperties().getDeliveryTag();
        channel.basicAck(deliveryTag,false);//true:批量确认,false确认当前消息
    }

}